// pages/mine/mine.js
let template = require('./../../template/tabbar.js');
import { saveNickNameAndAvatarAction, queryPersonalModule, loginWxAction } from "../../service/config"
import { getOANotReadNum } from "../../service/manager_service"
import { getMyWallet, queryMyQrCode } from "../../service/onetoone_service"

import {
  querGlobalConfig,
  queryMyVisitStoreList
} from "../../service/jb_home_service"
import {
  queryUserInfo,
  queryUserMenus
} from "../../service/jb_mine_service"
import {
  SERVICE_URL,
  SERVICE_ID,
} from "../../service/base_service"
import {
  getOrderCategoryNums
} from "../../service/jb_order_service.js"
import {
  MINETOPBG_IMG,
  LINGQUAN_IMG
} from "../../service/image_service"
import {
  getPersonReq
} from "../../service/jb_activity_service"
import {
  signPersonInfo,//今日签到信息
} from "../../service/jb_sign_service"
import {
  getMyPromotionCommission,
} from "../../service/jb_promotion_service"
import mathUtil from "../../tools/mathUtils/mathUtil"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    refreshFlag: false,
    mineToBg_img: MINETOPBG_IMG,
    lingQuan_img: LINGQUAN_IMG,
    themeStyle: "",
    lineWidth: "0%",
    isTodaySign: false,//今日是否签到
    //默认头像地址
    plaAvatarImg: "https://images.jiabao19.com/images/user/plaavatar.png",
    avatar: "",
    nickName: "",
    roleName: "",
    isLogin: false,
    companyNumber: "",
    balanceMoney: 0,//钱包余额
    contributeValue: 0,//贡献值
    showImgVideo: false,
    isShowQRCode: false,
    topNums: [

    ],
    myServices: [
      {
        title: "地址管理",
        num: 0,
        navUrl: "/shopMallPackage/pages/addressList/addressList",
        noLoginUrl: "/pages/login/login",
        icon: "/img/mine/mine_dzgl.png",
      },
      {
        title: "推广收益",
        num: 0,
        navUrl: "/featurePackage/pages/myLowers/myLowers",
        noLoginUrl: "/pages/login/login",
        icon: "/img/mine/mine_wdxj.png",
      },
      {
        title: "我的收藏",
        num: 0,
        noLoginUrl: "/pages/login/login",
        navUrl: "/featurePackage/pages/mySave/mySave",
        icon: "/img/mine/mine_wdscc.png"
      },
      // {
      //   title: "我的商品",
      //   num: 0,
      //   noLoginUrl: "/pages/login/login",
      //   navUrl: "/featurePackage/pages/myGoods/myGoods",
      //   icon: "/img/mine/mine_wdsc.png"
      // },
      {
        title: "我的小店",
        num: 0,
        navUrl: "/featurePackage/pages/mySmallShop/mySmallShop",
        noLoginUrl: "/pages/login/login",
        icon: "/img/mine/mine_wdxd.png",
      },
      {
        title: "我的优惠券",
        num: 0,
        navUrl: "/featurePackage/pages/couponList/couponList",
        noLoginUrl: "/pages/login/login",
        icon: "/img/mine/mine_wdyhq.png",
      },
      {
        title: "礼品卡",
        num: 0,
        noLoginUrl: "/pages/login/login",
        navUrl: "/featurePackage/pages/giftMain/giftMain",
        icon: "/img/mine/mine_lpk.png"
      },
      {
        title: "签到打卡",
        num: 0,
        noLoginUrl: "/pages/login/login",
        navUrl: "/featurePackage/pages/sign/signMain/signMain",
        icon: "/img/mine/mine_sign.png"
      },
      {
        title: "定制专区",
        num: 0,
        noLoginUrl: "/pages/login/login",
        // navUrl: "/featurePackage/pages/customArea/customArea",
        navUrl: '/featurePackage/pages/privateCustomList/privateCustomList',
        icon: "/img/mine/mine_dz.png"
      },
      {
        title: "关注公众号",
        num: 0,
        noLoginUrl: "/pages/login/login",
        navUrl: "/firstPackage/pages/officialAccounts/officialAccounts",
        icon: "/img/mine/mine_gzgzh.png"
      },
      {
        title: "企微客服",
        num: 0,
        noLoginUrl: "/pages/login/login",
        navUrl: "/firstPackage/pages/officialAccounts/officialAccounts",
        icon: "/img/mine/mine_kefu.png"
      },
      // {
      //   title: "OA管理",
      //   num: 0,
      //   noLoginUrl: "/pages/login/login",
      //   navUrl: "/featurePackage/pages/oaManager/oaMain/oaMain",
      //   icon: "/img/mine/mine_oagl.png"
      // },
    ],
    oaManager: {
      title: "OA管理",
      num: 0,
      noLoginUrl: "/pages/login/login",
      navUrl: "/featurePackage/pages/oaManager/oaMain/oaMain",
      icon: "/img/mine/mine_oagl.png"
    },
    activityManager: {
      title: "创新创业",
      num: 0,
      noLoginUrl: "/pages/login/login",
      navUrl: "/featurePackage/pages/myActivityList/myActivityList",
      icon: "/img/mine/mine_cy.png"
    },
    topNewThree: [
      {
        title: "待付款",
        num: 0,
        navUrl: "/shopMallPackage/pages/myOrderList/myOrderList?type=0",
        noLoginUrl: "/pages/login/login",
        icon: "/img/mine/order_dfk.png",
      },
      {
        title: "待发货",
        num: 0,
        navUrl: "/shopMallPackage/pages/myOrderList/myOrderList?type=1",
        noLoginUrl: "/pages/login/login",
        icon: "/img/mine/order_yfk.png",
      },
      {
        title: "待收货",
        num: 0,
        noLoginUrl: "/pages/login/login",
        navUrl: "/shopMallPackage/pages/myOrderList/myOrderList?type=2",
        icon: "/img/mine/order_yfh.png"
      },
      {
        title: "待评价",
        num: 0,
        navUrl: "/shopMallPackage/pages/myOrderList/myOrderList?type=3",
        noLoginUrl: "/pages/login/login",
        icon: "/img/mine/order_dpj.png"
      },
      //这个是单独跳转一个页面
      {
        title: "售后/退款",
        num: 0,
        navUrl: "/shopMallPackage/pages/myRefundOrderList/myRefundOrderList?type=0",
        icon: "/img/mine/order_ywc.png"
      }
    ],
    msgTotalNum: 0,
    topModules: [
      {
        title: "购物车",
        icon: "/img/common/minegwc_icon.png",
        navUrl: "/shopMallPackage/pages/shopCarList/shopCarList",
        noLoginUrl: "/pages/login/login",
        showRight: true,
        showText: "查看购物车"
      },

      {
        title: "在线客服",
        icon: "/img/common/minetwo_icon.png",
        navUrl: "/pages/message/message",
        noLoginUrl: "/pages/login/login",
        showRight: true,
        showText: '暂无消息'
      },
      {
        title: "我的活动",
        icon: "/img/common/minettt_icon.png",
        navUrl: "/shopMallPackage/pages/singUpActivity/singUpActivity",
        noLoginUrl: "/pages/login/login",
        showRight: false,
      },
      {
        title: "积分转赠",
        icon: "/img/common/minethree_icon.png",
        navUrl: "/shopMallPackage/pages/score/sendScore/sendScore",
        noLoginUrl: "/pages/login/login",
        showRight: false,
      },
      {
        title: "抵扣房款",
        icon: "/img/common/minefour_icon.png",
        navUrl: "/shopMallPackage/pages/bindingHouseList/bindingHouseList",
        noLoginUrl: "/pages/login/login",
        showRight: true,
        showText: "积分抵扣"
      },
      {
        title: "健康档案",
        icon: "/img/common/minefive_icon.png",
        navUrl: "/storePackage/pages/healthRecord/healthRecord",
        noLoginUrl: "/pages/login/login",
        showRight: true,
        showText: "体检报告"
      },
      {
        title: "收货地址",
        icon: "/img/common/minesex_icon.png",
        navUrl: "/shopMallPackage/pages/addressList/addressList",
        noLoginUrl: "/pages/login/login",
        showRight: true,
        showText: "更新"
      },
      {
        title: "银行卡绑定",
        icon: "/img/common/minenine_icon.png",
        navUrl: "/formPackage/pages/personalInfo/personalInfo",
        noLoginUrl: "/pages/login/login",
        showRight: true,
        showText: "更新"
      }
    ],
    //工作台
    toolModules: [

    ],
    //常用工具
    commonTools: [

    ],

    scrollRefreshStatus: true,
    showPosterImgView: false,
    posterImg: "",//海报图片
    menuHeight: 0,
    customActionStyle: {},
    menuTop: 0,
    companyName: "",
    oaTotalNumber: 0,//oa总的未读数量
    companyRecordNumber: 0,//公司报备数量
    //赋值的
    posterInfo: {},
    //改变值的:
    posterData: {
      "width": "690rpx",
      "height": "1095rpx",
      "background": "transparent",
      "views": [

      ]
    },
    showLineWidth: true,
    posterViews: [
      //背景图
      {
        "type": "image",
        "url": "https://saas.img.ylyc.top/poster/minetopposter_icon.png",
        "css": {
          "width": "690rpx",
          "height": "1095rpx",
          "top": "0rpx",
          "left": "0rpx",
          "rotate": "0",
          "borderRadius": "",
          "borderWidth": "",
          "shadow": "",
          "mode": ""
        }
      },
      //头像
      {
        "type": "image",
        "url": "",
        "css": {
          "width": "130rpx",
          "height": "130rpx",
          "top": "600rpx",
          "left": "98rpx",
          "rotate": "0",
          "borderRadius": "65rpx",
          "borderWidth": "",
          "borderColor": "#000000",
          "shadow": "",
          "mode": "aspectFill"
        }
      },
      //昵称
      {
        "type": "text",
        "text": "",
        "css": {
          top: "760rpx",
          left: "80rpx",
          textAlign: 'center',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "36rpx",
          "fontWeight": "bold",
          "color": "#000000",
        }
      },
      // 电话
      {
        "type": "text",
        "text": "",
        "css": {
          top: "832rpx",
          left: "130rpx",
          textAlign: 'left',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "28rpx",
          "fontWeight": "bold",
          "color": "#333333",
        }
      },
      // 微信
      {
        "type": "text",
        "text": "",
        "css": {
          top: "887rpx",
          left: "130rpx",
          textAlign: 'left',
          padding: '10rpx',
          scalable: true,
          deletable: true,
          "fontSize": "28rpx",
          "fontWeight": "bold",
          "color": "#333333",
        }
      },



      //个人二维码
      {
        "type": "image",
        "url": "",
        "css": {
          "width": "130rpx",
          "height": "130rpx",
          "bottom": "270rpx",
          "right": "95rpx",
          "rotate": "0",
          "borderRadius": "",
          "borderWidth": "",
          "borderColor": "#000000",
          "shadow": "",
          "mode": "aspectFill"
        }
      },
    ],
    onlineCustomer: {

    },//在线客服

    //入口滑动数组:
    swiperImgArr: [
      {
        path: "https://saas.img.ylyc.top/bg/newagencydail_icon.png",
        key: "daili",
        url: "/formPackage/pages/agencyModule/applyCityAgency/applyCityAgency",
      },
      {
        path: "https://saas.img.ylyc.top/bg/newagentjj_icon.png",
        key: "agency",
        url: "/formPackage/pages/enterApply/agentApply/agentApply",
      },
      {
        path: "https://saas.img.ylyc.top/bg/newcompanyc_icon.png",
        key: "company",
        url: "/formPackage/pages/enterApply/companyApply/companyApply",
      }
    ],
    swiperInterval: 5000,
    swiperDotIndex: 0,//滑块指示点位置
    vipExpertAtText: "",
    isLoading: false,
    isBindMp: false,
    qrCode: "",
    roleConfig: {},
    roleType: 0,//
    isShowScore: false,
    userInfo: {
      avatar: "",
      nickname: '',
      phone: '',
      level: 1,//最低等级
      promotionLevel: 0,// 如果这个值大于0，就代表是商户的第一个下级，就需要隐藏佣金那些东西
    },
    curPer: 0,
    perCur: 0,
    totalIncomeCount: 0,
    //订单数量
    orderNums: {
      "completeCount": 0,//已完成
      "evaluatedCount": 0,//待评价
      "orderCount": 0,//订单数量
      "receivedCount": 0,//待收货
      "refundCount": 0,//退款数量
      "sumPrice": "0",//订单消费总额
      "unPaidCount": 0,//待支付
      "unShippedCount": 0,//待发货
    },
    shareUserId: null,//分享id
    commissionConfig: {
      promoterLevels: [],
    },
    activtyRole: false,
    sumSignDay: 0,//累计签到天数
    isShowYY: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    template.tabbar("tabBar", 3, this, app.globalData.cartNum)//0表示第一个tabbar
    wx.hideTabBar();
    this.setData({
      menuTop: app.globalData.menuButton.top,
      menuHeight: app.globalData.menuButton.height,
      // plaAvatarImg: app.globalData.avatar || this.data.plaAvatarImg,
      roleConfig: app.globalData.roleConfig,
    })



    this.setData({
      isBindMp: app.globalData.isBindMp,
    })
    console.log("JJLog:当前微信公众号状态:" + this.data.isBindMp);
    // setTimeout(() => {
    //   if (!this.data.isBindMp && app.globalData.isLogin) {
    //     wx.showModal({
    //       title: '温馨提示',
    //       content: '关注公众号《万众卖房》即可查看详情、佣金变动、查看对接等',
    //       confirmColor: "#FF0000",
    //       confirmText: "前往关注",
    //       cancelText: "稍后关注",
    //       showCancel: true,
    //       success: res => {
    //         if (res.confirm) {
    //           wx.navigateTo({
    //             url: '/firstPackage/pages/officialAccounts/officialAccounts',
    //           })
    //         } else if (res.cancel) {
    //           wx.switchTab({
    //             url: '/pages/home/home',
    //           })
    //         }
    //       },

    //     })


    //   }
    // }, 2000)

  },

  //查询个人二维码
  queryMyQrCode() {
    queryMyQrCode().then(res => {
      console.log("JJLog:个人二维码是:" + JSON.stringify(res));
      if (res.code == 200) {
        app.globalData.qrCode = res.data || "";
        this.setData({
          qrCode: res.data || "",
        })
      }
    }).catch(err => {
      console.error("JJLog:queryMyQrCode", err);
      app.globalData.qrCode = "";
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //this.myWalletInfo();


    if (app.globalData.themeStyle) {
      this.setData({
        themeStyle: app.globalData.themeStyle
      })
    }
    this.setData({
      isLogin: app.globalData.isLogin
    })
    if (this.data.isLogin) {
      let name = "";
      name = app.globalData.name || app.globalData.nickName
      console.log("JJLog:roleType:" + app.globalData.roleType);

      this.setData({
        avatar: app.globalData.avatar,
        nickName: name || '',
        roleName: app.globalData.roleName,
      })

    }
    // this.getOANotReadNum();
    // //获取个人中心权限模块
    // this.queryPersonalModule();
    this.userWxLogin();
  },
  pushToSlist() {
    wx.navigateTo({
      url: '/featurePackage/pages/appointmentMyList/appointmentMyList',
    })
  },
  //获取个人信息api
  queryUserInfo() {
    queryUserInfo().then(res => {
      if (res.code == 200) {
        this.querGlobalConfig();
        this.setData({
          userInfo: res.data,
        })
        if (res.data.phone) {
          this.configHousePosterData();
        }

        if (res.data.oaRole) {
          this.dealOaShow();
        }
        //隐藏推广收益入口
        if (res.data.promotionLevel == 1) {
          this.hideTuiGuang();
        }

        app.globalData.userInfo = res.data
      }
    }).catch(err => {
      console.error("JJLog:queryUserInfo", err);
    })
  },
  //隐藏推广收益
  hideTuiGuang() {
    let arr = this.data.myServices;
    const url = "/featurePackage/pages/myLowers/myLowers";
    const isHave = arr.some(i => i.navUrl === url);
    if (isHave) {
      arr.splice(1, 1);
      this.setData({
        myServices: arr
      })
    }
  },
  //是否添加oa模块
  dealOaShow() {
    let arr = this.data.myServices;
    const url = "/featurePackage/pages/oaManager/oaMain/oaMain";
    const isHave = arr.some(i => i.navUrl === url);

    arr = isHave ? arr : [...arr, this.data.oaManager];
    this.setData({
      myServices: arr
    });

  },
  //是否添加作品发布入口
  dealActivityRole() {
    let arr = this.data.myServices;
    const url = "/featurePackage/pages/myActivityList/myActivityList";
    const isHave = arr.some(i => i.navUrl === url);

    arr = isHave ? arr : [...arr, this.data.activityManager];
    this.setData({
      myServices: arr
    });
  },
  //获取对应订单分类数量
  getOrderCategoryNums() {
    getOrderCategoryNums().then(res => {
      if (res.code == 200) {
        this.setData({
          orderNums: res.data
        })
        this.dealOrderNumShow(res.data);
      }
    }).catch(err => {
      console.error("JJLog:getOrderCategoryNums", err);
    })
  },
  dealOrderNumShow(orderData) {
    let arr = this.data.topNewThree;
    arr[0].num = orderData.unPaidCount || 0
    arr[1].num = orderData.unShippedCount || 0
    arr[2].num = orderData.receivedCount || 0
    arr[3].num = orderData.evaluatedCount || 0
    arr[4].num = orderData.refundCount || 0
    this.setData({
      topNewThree: arr
    })
  },
  //获取个人展示模块
  queryUserMenus() {
    queryUserMenus().then(res => {
      if (res.code == 200) {

      }
    }).catch(err => {
      console.error("JJLog:queryUserMenus", err);
    })
  },




  //获取个人中心权限模块:
  queryPersonalModule() {
    queryPersonalModule().then(res => {
      console.log("JJLog:获取到的个人中心配置是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data) {
          this.setData({
            toolModules: res.data["1"] || [],
            commonTools: res.data["2"] || []
          })
        }
      }
    }).catch(err => {
      console.error("JJLog:queryPersonalModule", err);
    })
  },


  //跳转到报备列表的对应状态:
  pushToReportAction(e) {
    let item = e.currentTarget.dataset.item;
    let name = item.name;
    let status = 2;
    if (name == "待到访") {
      status = 2;
    } else if (name == "待认购") {
      status = 3
    } else {
      status = 4
    }
    wx.navigateTo({
      url: '/firstPackage/pages/reportModule/reportRecord/reportRecord?status=' + status,
    })

  },
  //跳转到
  pushToMoneyPage(e) {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }

    let index = e.currentTarget.dataset.index;
    let navUrl = ""
    if (index == 0) {
      navUrl = "/featurePackage/pages/myScore/myScore"
    } else {
      navUrl = "/featurePackage/pages/myLowers/myLowers"
    }
    wx.navigateTo({
      url: navUrl,
    })
  },
  //订单模块跳转
  orderItemPush(e) {
    let item = e.currentTarget.dataset.item;
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }

    wx.navigateTo({
      url: item.navUrl
    })
  },
  //顶部模块跳转
  topModuleItemPush(e) {

    let item = e.currentTarget.dataset.item;
    if (item.title == "我的名片") {
      if (!app.globalData.isLogin) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
        return;
      }
      this.createProsterAction();
      return;
    }
    if (item.title == '我的邀请码') {
      if (!app.globalData.isLogin) {
        wx.navigateTo({
          url: '/pages/login/login',
        })
        return;
      }
      this.setData({
        isShowQRCode: true,
      })
      return;
    }
    let navUrl = item.navUrl;
    if (this.data.isLogin) {
      // wx.navigateTo({
      //   url: navUrl,
      // })
      this.authUserInfoAction(navUrl);
    } else {
      wx.navigateTo({
        url: item.noLoginUrl,
      })
    }

  },
  singItemPush(e) {
    let item = e.currentTarget.dataset.item;
    console.log(item.navUrl);
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    this.authUserInfoAction(item.navUrl);

    // wx.navigateTo({
    //   url: item.navUrl,
    // })
  },
  //创建海报:
  createProsterAction() {
    wx.showLoading({
      title: '海报生成中',
    })
    this.setData({
      posterInfo: this.data.posterData,
    })

  },
  //用户登陆授权等:
  userWxLogin() {
    loginWxAction().then((res => {
      console.log("JJLog:登录返回:" + JSON.stringify(res));
      let data = res.data;
      if (res.code == 200) {
        this.setData({
          isLoading: true,

        })
        app.globalData.nickName = data.nickname;
        app.globalData.avatar = data.avatar || "";

        app.globalData.phone = data.phone || "";
        app.globalData.isLogin = data.isLogin;

        this.setData({
          shareUserId: data.uid,
        })
        app.globalData.userId = data.uid;





        this.setData({
          refreshFlag: false,
          avatar: app.globalData.avatar,
          nickName: data.nickname,
          isLogin: app.globalData.isLogin,

        })
        if (this.data.isLogin) {
          this.queryUserInfo();
          this.queryUserMenus();
          this.getOrderCategoryNums();
          this.getPersonAction();//获取用户认证大学生信息
          this.getSignToday();//获取今日签到信息
          this.getMyPromotionCommission();
          this.queryMyVisitStoreList();
        }

      }
    })).catch(err => {
      console.error("JJLog:userWxLogin", err);
      this.setData({
        refreshFlag: false
      })
    })
  },
  queryMyVisitStoreList() {
    queryMyVisitStoreList(app.globalData.userId).then(res => {
      if (res.code == 200) {
        if (res.data.list && res.data.list.length > 0) {
          this.setData({
            isShowYY: true,
          })
        }
      }
    })
  },
  getMyPromotionCommission() {
    getMyPromotionCommission().then(res => {

      if (res.code == 200) {
        let totalCount = mathUtil.add(res.data.commissionCount, res.data.preCommission)
        totalCount = mathUtil.add(totalCount, res.data.frozenPrice)
        totalCount = mathUtil.add(totalCount, res.data.extractCount)
        totalCount = mathUtil.add(totalCount, res.data.extractingCommission || 0)

        this.setData({
          totalIncomeCount: totalCount,
        })

      }
    }).catch(err => {

      console.error('JJLog:getMyPromotionCommission', err);
    })
  },
  getSignToday() {
    signPersonInfo().then(res => {
      if (res.code == 200) {
        this.setData({
          isTodaySign: res.data.isDaySign,
          sumSignDay: res.data.sumSignDay || 0
        })
      }
    }).catch(err => {

    })
  },
  pushToSignEnter() {
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }
    wx.navigateTo({
      url: '/featurePackage/pages/sign/signMain/signMain',
    })
  },
  getPersonAction() {
    getPersonReq().then(res => {
      if (res.code == 200) {
        if (res.data) {
          if (res.data.examineStatus == 1) {
            this.setData({
              activtyRole: true,
            })
            //是否有创业活动入口
            this.dealActivityRole();
          }
        } else {
          this.setData({
            activtyRole: false,
          })
        }


      }
    }).catch(err => {

    })
  },
  querGlobalConfig() {
    querGlobalConfig().then(res => {
      if (res.code == 200) {
        this.setData({
          commissionConfig: res.data
        })
        let curIndex = 0;
        if (res.data.promoterLevels && res.data.promoterLevels.length > 0) {
          res.data.promoterLevels.forEach((i, index) => {
            if (i.level == this.data.userInfo.promoterLevel) {
              curIndex = index;
            }
          })
        }
        if (curIndex == res.data.promoterLevels.length - 1) {
          //证明已经是最后等级。就不显示进度条了
          this.setData({
            showLineWidth: false,

          })
          app.globalData.levelData = {
            isMax: true,
          }
          return;
        }
        let curPer = this.data.userInfo.promoterExperience;
        let perCur = res.data.promoterLevels[curIndex + 1].upQuota
        app.globalData.levelData = {
          isMax: false,
          nextNum: perCur,//下个等级积分
          nextName: res.data.promoterLevels[curIndex + 1].levelName
        }
        console.log("JJLog:per是：" + perCur);
        //处理宽度
        let widthPercent = ((curPer / perCur) * 100) + "%"
        this.setData({
          lineWidth: widthPercent,
          curPer: curPer.split('.')[0],
          perCur: perCur.split('.')[0],
        })
      }
    }).catch(err => {
      console.error("JJLog:querGlobalConfig", err);
    })
  },
  pushToExperience() {
    wx.navigateTo({
      url: '/featurePackage/pages/myExperience/myExperience',
    })
  },

  getOANotReadNum() {
    getOANotReadNum().then(res => {
      console.log("JJLog:OA未读数量是:" + JSON.stringify(res));
      if (res.code == 200) {
        if (res.data) {
          let tempArr = [];
          for (let key in res.data) {
            let obj = {
              name: key,
              num: res.data[key] || 0,
            }
            tempArr.push(obj);
          }
          let totalNum = 0;
          tempArr.forEach((i) => {
            totalNum = totalNum + i.num;
          })
          this.setData({
            oaTotalNumber: totalNum,
          })
          // console.log("JJLog:oa数量赋值:" + this.data.oaTotalNumber);
        }
      }
    }).catch(err => {
      console.error("JJLog:getOANotReadNum", err);
    })
  },

  //跳转到登录页面
  pushToLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },


  //工作台跳转
  toolPushAction(e) {



    //如果登录后又没有授权头像资料，那么点击的时候，先走这里
    let item = e.currentTarget.dataset.item;
    if (item.title == '在线客服' || item.title == '企微客服') {
      if (item.title == '在线客服') {
        wx.openCustomerServiceChat({
          extInfo: { url: SERVICE_URL },
          corpId: SERVICE_ID,
          success(res) { },
          fail(err) {
            console.log('调用失败:', err);
          }
        })
      } else {
        wx.navigateTo({
          url: '/featurePackage/pages/companyWxService/companyWxService',
        })
      }

      return;
    }
    if (item.title == '关注公众号') {
      wx.navigateTo({
        url: item.navUrl,
      })
      return;
    }
    if (this.data.isLogin) {
      wx.navigateTo({
        url: item.navUrl,
      })
      return;
    }
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: item.noLoginUrl,
      })
    }
    // console.log("JJLog:item是:" + JSON.stringify(item));
    // this.authUserInfoAction(item.path);

    // if (this.data.isLogin) {
    //   wx.navigateTo({
    //     url: item.navUrl,
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: item.noLoginUrl,
    //   })
    // }

  },
  //常用工具跳转:
  commonPushAction(e) {



    let item = e.currentTarget.dataset.item;
    console.log("JJLog:" + JSON.stringify(item));
    if (item.menuName == "在线客服") {
      // if (JSON.stringify(this.data.onlineCustomer) != "{}") {
      //   if (!app.globalData.isLogin) {
      //     wx.navigateTo({
      //       url: '/pages/login/login',
      //     })
      //     return;
      //   }
      //   console.log("JJLog:" + JSON.stringify(e));
      //   let item = this.data.onlineCustomer;
      //   let chatData = {
      //     name: item.name || item.nickName,
      //     avatar: item.avatar,
      //     chatUserId: item.openId,
      //     conversationType: "C2C",
      //   }
      //   app.globalData.chatData = chatData;
      //   wx.navigateTo({
      //     url: '/firstPackage/pages/msgModule/chatRoom/chatRoom',
      //   })
      // } else {
      //   wx.showToast({
      //     title: '客服正忙，暂时无法咨询',
      //     icon: "none"
      //   })
      // }
    } else {
      this.authUserInfoAction(item.path);
    }


    // wx.navigateTo({
    //   url: item.path,
    // })
    // if (this.data.isLogin) {
    //   wx.navigateTo({
    //     url: item.navUrl,
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: item.noLoginUrl,
    //   })
    // }

  },
  //登录授权操作:
  authUserInfoAction(path) {
    return;
    if (this.data.isLogin && !app.globalData.isAuthUserInfo) {
      //登录了但是没有授权的:
      wx.getUserProfile({
        desc: "请求您的微信头像昵称授权",
        success: res => {
          console.log("JJLog:微信授权:" + JSON.stringify(res));
          app.globalData.isAuthUserInfo = true;
          saveNickNameAndAvatarAction(res.userInfo.nickName, res.userInfo.avatarUrl)
          // imTODO

          wx.navigateTo({
            url: path,
          })
        },
        fail: err => {
          console.log("JJLog:获取微信信息失败:" + JSON.stringify(err));
          wx.showToast({
            title: '授权才能继续操作',
            icon: "none"
          })
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/home/home',
            })
          }, 2000);
        }
      })
    } else {
      // console.log("JJLog:path是:" + path);

      wx.navigateTo({
        url: path,
      })
    }
  },


  //刷新数据:
  refreshDownData() {
    this.setData({
      scrollRefreshStatus: true,
    })

    this.userWxLogin();
    this.myWalletInfo();

  },

  //创建海报成功
  createPosterSuccess(e) {
    wx.hideLoading();
    wx.showToast({
      title: '生成成功',
      icon: "success"
    })

    this.setData({
      posterImg: e.detail.path,
      showPosterImgView: true
    });
  },
  //创建海报失败
  createPosterFail() {
    wx.hideLoading();
    wx.showToast({
      title: "海报生成失败",
      icon: "none"
    })
    console.error("JJLog:生成海报失败:" + JSON.stringify(e));
  },
  closePosterImg() {
    this.setData({
      showPosterImgView: false,
    })
  },
  //配置海报
  configHousePosterData() {
    //动态数组:
    let avatarItem = 'posterViews[' + 1 + '].url';
    let nikcItem = 'posterViews[' + 2 + '].text';
    let phoneItem = 'posterViews[' + 3 + '].text';
    let weChatItem = 'posterViews[' + 4 + '].text';
    let qrCodeItem = 'posterViews[' + 5 + '].url';
    let phone = "";
    if (this.data.userInfo.phone) {
      phone = this.data.userInfo.phone
    } else {
      phone = "";
    }
    let weChat = app.globalData.weChat || "";

    let nickName = this.data.userInfo.nickname
    if (nickName.length > 8) {
      nickName = nickName.substr(0, 8) + "...";
    }
    this.setData({
      [avatarItem]: this.data.userInfo.avatar,
      [nikcItem]: nickName,
      [phoneItem]: phone,
      [weChatItem]: weChat,
      [qrCodeItem]: app.globalData.qrCode || ""
    })
    this.setData({
      'posterData.views': this.data.posterViews
    })
  },
  //保存海报名片
  savePosterImg() {
    let that = this;
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              // 同意授权
              //保存到本地
              wx.saveImageToPhotosAlbum({
                filePath: this.data.posterImg,
                success(res) {
                  wx.showToast({
                    title: '保存海报成功',
                    icon: 'success',
                    duration: 2000
                  })
                  that.setData({
                    showPosterImgView: false
                  })
                },
                fail: (err) => {
                  console.log("JJLog:保存图片失败:" + JSON.stringify(err));
                  wx.showToast({
                    title: '保存海报失败',
                    icon: "none"
                  })
                }
              })
            },
            fail: (res) => {
              console.log(res);
              wx.showModal({
                title: '提示',
                content: '保存海报需要您同意访问您的相册',
                success(res) {
                  if (res.confirm) {
                    wx.openSetting();
                  } else if (res.cancel) {
                    // console.log('用户点击取消')
                  }
                }
              })


            }
          })
        } else {
          // 已经授权了
          //保存到本地
          wx.saveImageToPhotosAlbum({
            filePath: this.data.posterImg,
            success(res) {
              wx.showToast({
                title: '保存海报成功',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                showPosterImgView: false
              })
            },
            fail: (err) => {
              console.log("JJLog:保存图片失败:" + JSON.stringify(err));
              wx.showToast({
                title: '保存海报失败',
                icon: "none"
              })
            }
          })
        }
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
  handleRefresh() {
    this.setData({
      refreshFlag: true,
    })
    this.userWxLogin()
  },

  //编辑个人资料页面:
  pushToEditInfo() {
    wx.navigateTo({
      url: '/formPackage/pages/personalInfo/personalInfo',
    })
  },



  swiperChangeAction(e) {
    // console.log("JJLog:改变来:" + JSON.stringify(e));
    let current = e.detail.current;
    this.setData({
      swiperDotIndex: current
    })
  },


  //跳转到我的钱包:
  pushToMyWallet() {
    if (!this.data.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return;
    }

    this.authUserInfoAction("/shopMallPackage/pages/score/myScore/myScore")


  },
  //跳转到查看贡献值页面
  pushToConPage() {
    wx.navigateTo({
      url: '/formPackage/pages/team/contributeExplain/contributeExplain',
    })
  },




  //获取我的积分数据:
  myWalletInfo() {
    getMyWallet().then(res => {
      console.log("JJLog:钱包数据===:" + JSON.stringify(res));
      if (res.code == 200) {
        this.setData({
          balanceMoney: res.data.restMoney || 0,
        })
        app.globalData.balanceMoney = this.data.balanceMoney;
      }
    }).catch(err => {
      console.error("JJLog:getMyWallet", err);
    })
  },


  invitedTypeAction(e) {
    this.setData({
      showImgVideo: false
    })
    let type = e.currentTarget.dataset.type;
    if (type == "agent") {
      wx.navigateTo({
        url: '/formPackage/pages/platformModule/agencyInvitePage/agencyInvitePage',
      })
    } else {
      wx.navigateTo({
        url: '/formPackage/pages/platformModule/companyInvitePage/companyInvitePage',
      })
    }
  },


  //复制公司编号:
  copyWxChatAction() {

    wx.setClipboardData({
      data: this.data.companyNumber,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制编号成功'
            })
          },
          fail: function (err) {
            wx.showToast({
              title: '复制失败',
              icon: "none"
            })
          }
        })
      }
    })

  },
  // 跳转到积分说明页面:
  pushToScoreExplain() {
    if (app.globalData.scoreInfo) {
      wx.navigateTo({
        url: '/shopMallPackage/pages/score/scoreExplain/scoreExplain',
      })
    } else {
      wx.showToast({
        title: '暂无积分说明',
        icon: "none"
      })
    }

  },
  hideQRPopup() {
    this.setData({
      isShowQRCode: false
    })
  },
  popupHide() {
    this.setData({
      showImgVideo: false
    })
  },
  pushToCouponAction() {
    wx.navigateTo({
      url: '/featurePackage/pages/getCouponList/getCouponList',
    })
  },
  //跳转至全部订单
  pushToAllOrder() {
    if (!app.globalData.isLogin) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    wx.navigateTo({
      url: '/shopMallPackage/pages/myOrderList/myOrderList?type=0',
    })
  },
})